<?php
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Worker\Controller;
use Think\Model;

/**
 * 后台登录控制器
 * @author derek <693472824@qq.com>
 */
class PublicController extends BaseController {

    /**
     * 发送验证码
     * @param integer account   手机号
     * @param integer type      操作类型 1：新注册；2：找回密码
     * @author derek <693472824@qq.com>
     */
    public function validate(){
        
        $account = I('POST.account');
        $type = I('POST.type');
        
        if(!checkMobile($account) || !in_array($type, array('1', '2'))){
            $this->rsp['rspCode'] = '422';
            $this->rsp['rspDesc'] = '参数异常';
            exit(json_encode($this->rsp));
        }
        
        //是否被禁止发送验证码
        $forbidden = false;
        
        $workerModel = M('Worker')->where(array('account'=>$account))->find();
        
        if($type == '1' && !(empty($workerModel) || ($workerModel['member_type'] == '1' && $workerModel['status'] == '5'))){
        
            $this->rsp['rspCode'] = '108';
            $this->rsp['rspDesc'] = '账号已被注册';
            exit(json_encode($this->rsp));
        }elseif($type == '2' && (empty($workerModel) || ($workerModel['member_type'] == '1' && $workerModel['status'] == '5'))){
        
            $this->rsp['rspCode'] = '109';
            $this->rsp['rspDesc'] = '账号不存在';
            exit(json_encode($this->rsp));
        }
        
        $effectiveTime = C('EFFECTIVE_TIME') ? C('EFFECTIVE_TIME') : 30;
        $validateInfo = S('validate.'.$account);
        
        if($validateInfo){
        
            $maxFrequency = C('MAX_VALIDATE_CODE_FREQUENCY') ? C('MAX_VALIDATE_CODE_FREQUENCY') : 10;
            $count = $validateInfo['count'] + 1;
        
            //有效时间（EFFECTIVE_TIME）内，发送验证码超越规定次数（MAX_VALIDATE_CODE_FREQUENCY）时，限制账号EFFECTIVE_TIME分钟
            if(NOW_TIME - $validateInfo['starttime'] < $effectiveTime * 60 && $count > $maxFrequency){
                $forbidden = true;
                $this->rsp['rspCode'] = '102';
                $this->rsp['rspDesc'] = '发送验证码太频繁';
                exit(json_encode($this->rsp));
            }
        }
        
        //生成验证码
        $validation = rand(100000, 999999);
        $message = C('VALIDATE_MESSAGE') ? C('VALIDATE_MESSAGE') : '您此次的验证码为：#code#，#effective#分钟内有效！';
        
        $message = str_replace('#code#', $validation, $message);
        $message = str_replace('#effective#', $effectiveTime, $message);
        
        $result =  api('Util/sendCode', array($account, $message));

        if($result){
        
            $validateInfo['starttime'] = $validateInfo['starttime'] ? $validateInfo['starttime'] : NOW_TIME;
            $validateInfo['count'] = $validateInfo['count'] ? $validateInfo['count'] + 1 : 1;
            $validateInfo['validation'] = $validation;
            S('validate.'.$account, $validateInfo, $effectiveTime * 60);
        
            $this->rsp['rspCode'] = '200';
            $this->rsp['rspDesc'] = '发送成功';
        }else{
        
            $this->rsp['rspCode'] = '303';
            $this->rsp['rspDesc'] = '发送失败，请重新发送';
        }
        
        exit(json_encode($this->rsp));
    }
    
    /**
     * 用户注册/重置密码
     * @param integer account       手机号
     * @param integer validation    验证码
     * @param integer password      密码
     * @author derek <693472824@qq.com>
     */
    public function register() {
        
        $account = I('POST.account');
        $validation = I('POST.validation');
        $password = I('POST.password');
        $type = I('POST.type');
        
        if(!checkMobile($account) || !preg_match("/^[1-9][0-9]{5}$/", $validation)){
            $this->rsp['rspCode'] = '422';
            $this->rsp['rspDesc'] = '参数异常';
            exit(json_encode($this->rsp));
        }
        
        //账号-验证码信息
        $validateInfo = S('validate.'.$account);
        
        if(!is_array($validateInfo) || $validation <> $validateInfo['validation']){
            $this->rsp['rspCode'] = '103';
            $this->rsp['rspDesc'] = '验证码错误';
            exit(json_encode($this->rsp));
        }

        $worker = D('Worker');
        $workerModel = $worker->where(array('account'=>$account))->find();
        
        //type  1：新注册；2：重置密码
        if($type == '1' && !(empty($workerModel) || ($workerModel['member_type'] == '1' && $workerModel['status'] == '5'))){
        
            $this->rsp['rspCode'] = '108';
            $this->rsp['rspDesc'] = '账号已被注册';
            exit(json_encode($this->rsp));
        }elseif($type == '2' && (empty($workerModel) || ($workerModel['member_type'] == '1' && $workerModel['status'] == '5'))){
        
            $this->rsp['rspCode'] = '109';
            $this->rsp['rspDesc'] = '账号不存在';
            exit(json_encode($this->rsp));
        }
        
        //闲散小哥注册
        if($type == '1' && empty($workerModel)){
            
            $opType = Model::MODEL_INSERT;
            $data['account'] = $account;
            $data['telphone'] = $account;
            $data['member_type'] = '2';
            $data['status'] = '2';              //闲散小哥待完善信息
            
        }elseif(($type == '1' && $workerModel['member_type'] == '1') || ($type == '2' && $workerModel['status'] != '5')){
            
            //自有团队成员注册 或 所有小哥修改密码
            $opType = Model::MODEL_UPDATE;
            
            //自有团队成员注册后，状态即为正常
            if($type == '1' || ($type == '2' && $workerModel['status'] == '0')){
                $data['status'] = '1';
            }
        }else{
            
            //不操作数据库
            $opType = '6';          
        }
        
        $data['password'] = $password;
        
        if($worker->create($data, $opType)){
            if($opType == '1'){
                
                $result = $worker->add();
            }else if($opType == '2'){
                
                $result = $worker->where(array('account'=>$account))->save();
            }
            
            if($result !== false){
                $this->rsp['rspCode'] = '200';
                
            }else{
                $this->rsp['rspCode'] = '301';
                $this->rsp['rspDesc'] = $worker->getError();
            }
        }else{
            
            $this->rsp['rspCode'] = '301';
            $this->rsp['rspDesc'] = $worker->getError();
        }
        
        exit(json_encode($this->rsp));
    }
    
    /**
     * 小哥登录
     * @param integer account       手机号
     * @param integer password      密码
     * @author derek <693472824@qq.com>
     */
    public function login(){
        
        $account = I('POST.account');
        $password = I('POST.password');
        
        if(!checkMobile($account)){
            $this->rsp['rspCode'] = '422';
            $this->rsp['rspDesc'] = '参数异常';
            exit(json_encode($this->rsp));
        }
        
        $worker = D('Api/WorkerView')->where(array('account'=>$account))->find();

        if(empty($worker) || $worker['status'] == '5'){
            
            $this->rsp['rspCode'] = '109';
            $this->rsp['rspDesc'] = '账号不存在';
        }else if($worker['status'] == '3'){
            
            $this->rsp['rspCode'] = '413';
            $this->rsp['rspDesc'] = '请联系客服确认培训事宜';
        }elseif($worker['status'] == '4'){
            
            $this->rsp['rspCode'] = '414';
            $this->rsp['rspDesc'] = '请联系客服确认审核信息';
            
        }elseif(in_array($worker['status'], array('1', '2')) && think_ucenter_md5($password, WORKER_AUTH_KEY) === $worker['password']){
            
            //多次尝试后登录成功，需清空失败次数
            S('forget.pwd.'.$account, null);
            
            //保存用户登录信息一周
            $token = md5(time().$account);
            S('token.'.$account, $token);
            
            //每年的平均工时和总单数清零后重新统计，因此 initTime 为年初时间戳
            $avgHour = D('Worker', 'Logic')->updateHour($worker['worker_id']);
            
            $worker['token'] = $token;
            $worker['avg_hour'] = $avgHour;
            $worker['fullpath'] = $worker['fullpath'] ? $worker['fullpath'] : '';
            $worker['job_name'] = get_dictionary_enum_name('job_options', $worker['job']);
            $worker['profession_name'] = get_dictionary_enum_name('profession_options', $worker['profession']);
            
            if($worker['status'] == '2'){
                $this->rsp['rspCode'] = '412';
            }elseif ($worker['status'] == '1'){
                $this->rsp['rspCode'] = '200';
            }
            
            unset($worker['password']);
            unset($worker['status']);
            
            $this->rsp['rspCont'] = $worker;
        }else{
            
            $count = S('forget.pwd.'.$account) ? S('forget.pwd.'.$account) + 1 : 1;
            if($count > 5){
                M('Worker')->where(array('account'=>$account))->setField('status', '0');
                $this->rsp['rspCode'] = '415';
                $this->rsp['rspDesc'] = '账号被锁定，请重置密码';
            }else{
                S('forget.pwd.'.$account, $count, 1800);
                $this->rsp['rspCode'] = '410';
                $this->rsp['rspDesc'] = '登录验证失败，请重试';
            }
        }
        
        exit(json_encode($this->rsp));
    }
    
    /**
     * 用户登录
     * @param integer account       手机号
     * @param string  token         token
     * @author derek <693472824@qq.com>
     */
    public function logout(){
        
        $account = I('POST.account');
        $token = I('POST.token');
        
        if($this->checkToken($account, $token)){
            
            S('token.'.$account, null);
            
            $this->rsp['rspCode'] = '200';
            
        }else{
            
            $this->rsp['rspCode'] = '409';
            $this->rsp['rspDesc'] = '账号验证失败';
        }
        
        exit(json_encode($this->rsp));
    }
    
    /**
     * 小哥填写入驻申请
     */
    public function apply(){
        
        $data = I();
        
        $account = I('POST.account');
        $token = I('POST.token');
        
        if($this->checkToken($account, $token)){
        
            if(empty($data['name']) || empty($data['profession']) || !is_numeric($data['job'])){
                $this->rsp['rspCode'] = '422';
                $this->rsp['rspDesc'] = '参数异常';
                exit(json_encode($this->rsp));
            }
            
            $workerModel = D('Worker');
            $worker = $workerModel->where(array('account'=>(string)$data['account']))->find();
            
            if($worker['status'] == '2' && $worker['member_type'] == '2'){
            
                $data['status'] = '3';
                if($workerModel->field('name,telphone,sex,birthday,province,city,referee,job,profession,status')->create($data)){
            
                    $result = $workerModel->where(array('account'=>$account))->save();
                }
            }
            
            if($result !== false){
                $this->rsp['rspCode'] = '200';
                S('token.'.$account, null);
            }else{
                $this->rsp['rspCode'] = '301';
                $this->rsp['rspDesc'] = '操作数据库异常';
            }
        }else{
        
            $this->rsp['rspCode'] = '409';
            $this->rsp['rspDesc'] = '账号验证失败';
        }
        
        exit(json_encode($this->rsp));
    }
    
    /**
     * 获取枚举值（小哥职业、技术专长）信息
     */
    public function enumList(){
        
        $dictName = I('POST.name');
        
        $list = array();
        
        if($dictName === 'job'){
            
            $name = 'job_options';
        }elseif ($dictName === 'profession'){
            
            $name = 'profession_options';
        }else{
            $name = 'null';
        }
        
        $list = get_dictionary_enum($name);
        empty($list) ? array() : sort($list);
        
        $this->rsp['rspCode'] = '200';
        $this->rsp['rspCont'] = $list;
        
        exit(json_encode($this->rsp));
    }
    
    /**
     * 关于我们文字提示
     */
    public function aboutus(){
        
        $about = C('ABOUT_US');
        
        $this->rsp['rspCode'] = '200';
        $this->rsp['rspCont'] = $about;
        
        exit(json_encode($this->rsp));
    }
    
}
